﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace Fwql.Net.Extensions
{
    public static class ExceptionExtension
    {
        /// <summary>
        /// 返回原始(最底层)异常对象
        /// </summary>
        /// <param name = "exception"></param>
        /// <returns></returns>
        public static Exception GetOriginalException(this Exception exception)
        {
            while (exception.InnerException != null)
                exception = exception.InnerException;
            return exception;
        }

        ///<summary>
        /// 返回所有异常消息列表
        ///</summary>
        ///<param name="exception">异常对象</param>
        ///<returns></returns>
        /// <remark>
        /// 越底层的异常在返回集合对象的位置越靠前
        /// </remark>
        public static IEnumerable<string> Messages(this Exception exception)
        {
            return exception != null
                       ? new List<string>(exception.InnerException.Messages())
                         {
                             exception.Message
                         }
                       : Enumerable.Empty<string>();
        }

        ///<summary>
        /// 返回所有异常列表
        ///</summary>
        ///<param name="exception">异常对象</param>
        ///<returns></returns>
        /// <remark>
        /// 越底层的异常在返回集合对象的位置越靠前
        /// </remark>
        public static IEnumerable<Exception> Exceptions(this Exception exception)
        {
            return exception != null
                       ? new List<Exception>(exception.InnerException.Exceptions())
                         {
                             exception
                         }
                       : Enumerable.Empty<Exception>();
        }
    }
}